package util;

import lombok.SneakyThrows;

import java.sql.*;
import java.util.Objects;


/**
 * @classname:DBHelper
 * @description:
 * @author: Mr.Z
 * @date: 2020/12/29 20:04
 * @version: 0.1
 * @since:1.8
 */
public class DBHelper {
    private DBHelper(){}
    private static final ThreadLocal<Connection> THREAD_LOCAL = new ThreadLocal(){
        @SneakyThrows
        @Override
        protected Connection initialValue() {
            return DriverManager.getConnection(PropUtil.getValue("url"),PropUtil.getValue("username"),PropUtil.getValue("password"));
        }
    };


    public static Connection getCon(){
        return THREAD_LOCAL.get();
    }
    public static void closeResources(Connection connection,PreparedStatement ps){
        Objects.requireNonNull(connection);
        Objects.requireNonNull(ps);
        try {
            ps.close();
            connection.close();
            THREAD_LOCAL.remove();
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }
    public static void closeResources(Connection connection, PreparedStatement ps, ResultSet resultSet){
        Objects.requireNonNull(connection);
        Objects.requireNonNull(ps);
        Objects.requireNonNull(resultSet);
        try {
            resultSet.close();
            ps.close();
            connection.close();
            THREAD_LOCAL.remove();
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }


}
